//
//  AddCar_Skus_Vc.swift
//  MikerShop
//
//  Created by eme on 2016/12/23.
//  Copyright © 2016年 eme. All rights reserved.
//

/*
 owner:cy
 update:2016年12月07日14:49:17
 info: 添加到购物车的弹出界面
 */
import RxSwift
import UtilCore
import RickonCore
import BrandonCore

class AddCar_Skus_Vc: Base_Vc {
    
    /****************************Storyboard UI设置区域****************************/
    @IBOutlet weak var dimBackgroundView: UIView!
    
    @IBOutlet weak var sheetView: UIView!
    
    @IBOutlet weak var content_V: UIView!
    
    @IBOutlet weak var productLogo_ImgV: UIImageView!

    @IBOutlet weak var header_SeperateLine_V: UIView!
    /// 商品价格
    @IBOutlet weak var price_Lb: UILabel!

    
    @IBOutlet weak var editNum_Lb: UILabel!
    
    @IBOutlet weak var totalPrice_Lb: UILabel!
    
    
    @IBOutlet weak var addCar_Tv: UITableView!
    
    @IBOutlet weak var footer_Buttons_Cv: UICollectionView!
    
    @IBOutlet weak var footer_SeperateLine_V: UIView!
    
    @IBOutlet weak var close_Btn: UIButton!
    
    ///用于缓存购买的总数量
    var total_EditNum:Int = 0
    
    ///混批按钮默认未选中
    @IBOutlet weak var hp_State_Btn: UIButton!
    var footerButtons:[Footer_Button_Model] = []
    /*----------------------------   自定义属性区域    ----------------------------*/
    
    //String ismix 0,否,1是
    // params:["osCarts":"","ismix":"1"]
    var saveProducts:((_ product:ProductModel,_ params:[String : Any],_ clickType:String) -> Void)?
    var productModel:ProductModel?{
        didSet{
            self.updateSubViewByModel()
        }
    }
    var skusArr = [SkusModel](){
        didSet{
            self.addCar_Tv.reloadData()
        }
    }
    
    var relParamArr:[[String:String]]{
        get{
            var sparmArr:[[String:String]] = []
            guard let user = AppData.loginedUser else {
                return []
            }
            guard let productModel = self.productModel else {
                return []
            }
            for item in productModel.skus {
                var relItem :[String:String] = [:]
                relItem["spid"] = "\(user.glShop.spid!)"
                relItem["brid"] = "\(productModel.brid)"
                relItem["pdid"] = "\(productModel.pdid)"
                relItem["skuid"] = "\(item.skuid)"
                relItem["cartnumber"] = "\(item.editnum)"
                relItem["ismix"] = productModel.isHp ? "1":"0"
                if item.editnum > 0 {
                    sparmArr.append(relItem)
                }
            }
            return sparmArr
        }
    }
    /****************************Storyboard 绑定方法区域****************************/
    
    
    
    /**************************** 以下是方法区域 ****************************/
    override func viewDidLoad() {
        super.viewDidLoad()
        self.modalPresentationStyle = .custom
        self.modalTransitionStyle = .coverVertical
        self.transitioningDelegate = self
        dimBackgroundView.backgroundColor = UIColor (white: 0, alpha: 0.4)
        dimBackgroundView.alpha = 0
        
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    @IBAction func dissmissVc(_ sender: Any) {
        self.dismiss()
    }
    /// 通过model 更新界面数据
    func updateSubViewByModel() -> Void {
        guard let model = self.productModel else {
            return
        }
        self.skusArr = model.skus
        if self.isJrdhdSingle() {
            self.hp_State_Btn.isEnabled = false
            self.hp_State_Btn.isHidden = true
            model.isHp = false
        }else{
            self.hp_State_Btn.isEnabled = true
            self.hp_State_Btn.isHidden = false
            self.hp_State_Btn.setTitle("混批（单sku起批量为1，总数量需满足：\(model.mixmoq)的倍数）", for: .normal)
            self.hp_State_Btn.isSelected = model.isHp
            self.updateFooteBtnState(self.hp_State_Btn.isSelected)
        }
        self.productLogo_ImgV.setUrlImage(model.img)
        switch model.priceType {
        case 1:
            self.price_Lb.text = model.price.getPriceStr()
        case 2:
            self.price_Lb.text = "\(model.priceMin.getPriceStr()) - \(model.priceMax.getPriceStr())"
        default:
            self.price_Lb.text = model.price.getPriceStr()
        }
        self.updateEditNumAndPrice()
 
    }
    ///判断是否是单个显示加入进货单
    func isJrdhdSingle() -> Bool {
        if self.footerButtons.count == 1 {
            let item = self.footerButtons[0]
            if item.type == "jrphd" {
                return true
            }
        }
        return false
    }
    /**
     界面基础设置
     */
    override func setupUI() {
        ///隐藏滑动条
        self.footer_Buttons_Cv.showsVerticalScrollIndicator = false
        header_SeperateLine_V.backgroundColor = Theme.v.bg_color
        footer_SeperateLine_V.backgroundColor = Theme.v.bg_color
        
    }
    
    /**
     绑定到viewmodel 设置
     */
    override func bindToViewModel(){
        self.close_Btn
            .rx.tap
            .subscribe(onNext: { [unowned self] ( _ ) in
                self.dismiss()
            })
            .disposed(by: disposeBag)
        
        self.hp_State_Btn
            .rx.tap
            .subscribe(onNext: { [unowned self] ( _ ) in
                self.hp_State_Btn.isSelected = !self.hp_State_Btn.isSelected
                self.productModel?.isHp = self.hp_State_Btn.isSelected
                self.updateSubViewByModel()

            })
            .disposed(by: disposeBag)
    }
    /// 混批时 加入进货单按钮不可点击
    func updateFooteBtnState(_ isHp:Bool) {
        for item  in self.footerButtons {
            ///如果是混批时 加入进货单不可以点击
            if item.type == "jrphd" {
                item.btnIsEnable = !isHp
                self.footer_Buttons_Cv.reloadData()
                break
            }
        }
    }
    
    func updateEditNumAndPrice() -> Void {
        
        var totalPrice:Double = 0.0
        var totalEditNum:Int = 0
        
        for item in self.skusArr {
            totalPrice = totalPrice + item.itemPrice
            totalEditNum = totalEditNum + item.totalNum
        }
        self.editNum_Lb.text = "共\(totalEditNum)\(self.productModel!.unit)"
        self.totalPrice_Lb.text = totalPrice.getPriceStr()
        self.total_EditNum = totalEditNum
    }
}
extension AddCar_Skus_Vc{
    func dismiss() {
        
        self.dismiss(animated: true, completion: nil)
    }
    
}
// MARK: UITableViewDelegate
extension AddCar_Skus_Vc :UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return self.skusArr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        let cell = tableView.dequeueReusableCell(withIdentifier: "AddCarTCell", for: indexPath) as!AddCarTCell
        cell.item = self.skusArr[indexPath.row]
        cell.didUpdate_Closure  = {[unowned self] item in
            self.updateEditNumAndPrice()
        }
        return cell
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
}
// MARK: UITableViewDelegate
extension AddCar_Skus_Vc: UITableViewDelegate {
    /// 点击行事件
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
        return 75
    }
    
}
extension AddCar_Skus_Vc: UIViewControllerTransitioningDelegate {
    public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return AddCar_Skus_PressentAnimator()
    }
    
    public func AddCar_SkuOne_DismissAnimator(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return AddCar_Skus_DismissAnimator()
    }
}
class AddCar_Skus_PressentAnimator:  NSObject, UIViewControllerAnimatedTransitioning {
    
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval{
        return 0.7
    }
    // This method can only  be a nop if the transition is interactive and not a percentDriven interactive transition.
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning){
        //1.获取动画的源控制器和目标控制器
        let fromVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)!
        let toVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) as! AddCar_Skus_Vc
        let containerView = transitionContext.containerView
        // start animation status
        toVC.dimBackgroundView.alpha = 0
        toVC.sheetView.frame = CGRect (x: fromVC.view.frame.origin.x,
                                       y: fromVC.view.frame.size.height,
                                       width: fromVC.view.frame.size.width,
                                       height: fromVC.view.frame.size.height)
        containerView.addSubview(toVC.view)
        let duration: TimeInterval = transitionDuration(using: transitionContext)
        // 执行动画
        UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0.0, options: .curveLinear, animations: {
            toVC.dimBackgroundView.alpha = 1
            toVC.sheetView.frame = transitionContext.finalFrame(for: toVC)
            }, completion: { (finished) in
                transitionContext.completeTransition(true)
        })
    }
    
}

class AddCar_Skus_DismissAnimator:  NSObject, UIViewControllerAnimatedTransitioning {
    
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval{
        return 0.7
    }
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning){
        let fromVC: AddCar_Skus_Vc = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) as!AddCar_Skus_Vc
        
        // start animation status
        fromVC.dimBackgroundView.alpha = 1
        let duration: TimeInterval = transitionDuration(using: transitionContext)
        let finalY: CGFloat = fromVC.view.frame.size.height
        
        // 执行动画
        UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0.0, options: .curveLinear, animations: {
            fromVC.dimBackgroundView.alpha = 0
            fromVC.sheetView.frame.origin.y += finalY
            }, completion: { (finished) in
                transitionContext.completeTransition(true)
        })
    }
    
}
// MARK: - UICollectionViewDataSource
extension AddCar_Skus_Vc:UICollectionViewDataSource{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
        if collectionView == footer_Buttons_Cv{
            return footerButtons.count
        }else{
            return 0
        }
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{
        if collectionView == footer_Buttons_Cv{
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Footer_Button_CCell", for: indexPath as IndexPath) as!Footer_Button_CCell
            cell.item = self.footerButtons[indexPath.row]
            cell.didClicked_Closure = {[unowned self] clicktype in
                if let saveProducts = self.saveProducts{
                    let relParamArr = self.relParamArr
                    /// 判断是否添加过商品
                    guard relParamArr.count > 0 else {
                        return self.view.toastErrorCode(100041001)
                    }
                    guard let model = self.productModel else {
                        return
                    }
                    if model.isHp {
                        guard model.mixmoq != 0 else {
                            return self.view.toast("混批参数错误~")
                        }
                        if self.total_EditNum % model.mixmoq == 0{
                            self.dismiss(animated: true){
                                saveProducts(model,["ismix":"1","osCarts":JSONHelper.parseToJson(relParamArr as AnyObject)] ,clicktype)
                            }
                        }else{
                            return self.view.toast("混批（单sku起批量为1，总数量需满足：\(model.mixmoq)的倍数）")
                        }
                    }else{
                        self.dismiss(animated: true){
                            saveProducts(model,["ismix":"0","osCarts":JSONHelper.parseToJson(relParamArr as AnyObject)] ,clicktype)
                        }
                    }
                }
            }
            return cell
        }
        return UICollectionViewCell()
    }
    func numberOfSections(in collectionView: UICollectionView) -> Int{
        if collectionView == footer_Buttons_Cv{
            return 1
        }else{
            return 0
        }
    }
}
extension AddCar_Skus_Vc:UICollectionViewDelegate{
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){
        
    }
}

extension AddCar_Skus_Vc:UICollectionViewDelegateFlowLayout{
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize{
        if collectionView == footer_Buttons_Cv{
            return CGSize(width: self.footer_Buttons_Cv.frame.width/CGFloat(footerButtons.count), height: self.footer_Buttons_Cv.frame.height)
        }else{
            return CGSize.zero
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets{
        return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat{
        return 0
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat{
        return 0
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize{
        return CGSize.zero
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize{
        return CGSize.zero
    }
}
